package com.acme.chat.db;

import java.util.List;

import org.apache.log4j.Logger;

import com.acme.chat.client.ChatClient;
import com.acme.chat.message.ChatMessage;
import com.acme.chat.message.Message;
import com.acme.chat.message.MessageType;
import com.acme.chat.message.PrivateMessage;
import com.acme.chat.util.BlockingQueue;
import com.acme.chat.util.Utils;


public class PrivateManager implements Runnable {
    private static final String ERROR_STOP_SAVE_MESSAGES = "Stop save messages!";
    private static Logger privateLogger = Logger.getLogger(PrivateManager.class.getName());

    private DbAdapter dbAdapter;
    private BlockingQueue messages = new BlockingQueue();

    private volatile boolean keepGoing;

    public PrivateManager() {
        dbAdapter = DbAdapter.getInstance();
        dbAdapter.connect();
        dbAdapter.prepareDb();
        keepGoing = true;
        new Thread(this).start();
    }

    private void savePrivateMessage(final String from, String to, String message) {
        messages.offer(new PrivateMessage(from, to, System.currentTimeMillis(), message));
    }

    private void print(String message){
    	privateLogger.info(message);
    }

    public void sendPrivateMessage(ChatClient from, ChatClient to, String toName, Message message) {
        String composeString = Utils.getCurrentTimeFormatted() + ": private " + from.getName() + ": " + message.getMessage();
        Message privateMessage = new ChatMessage(MessageType.MESSAGE, composeString);
        from.sendMessage(privateMessage);

        if (to != null) { to.sendMessage(privateMessage); }
        savePrivateMessage(from.getName(), toName, message.getMessage());
        print(composeString);
    }

    public void sendHistory(ChatClient client) {
        List<String> historyList = dbAdapter.getPrivateMessages(client.getName());
        StringBuilder history = new StringBuilder(Message.MAX_MESSAGE_LENGTH);
        history.append("Your private history:\n");
        for(String historyLine : historyList) {
            history.append(historyLine).append("\n");
        }
        client.sendMessage(new ChatMessage(MessageType.MESSAGE, history.toString()));
    }

    /**
     * Method drop saved data and close connection to DB.
     */
    public void close() {
        dbAdapter.close();
        keepGoing = false;
    }

    /**
     *
     */
    @Override
    public void run() {
        while(keepGoing) {
            try {
                PrivateMessage message = messages.poll();
                dbAdapter.savePrivateMessage(message);
            } catch (InterruptedException e) {
                print(ERROR_STOP_SAVE_MESSAGES);
                print(e.getMessage());
                break;
            }
        }
    }

}
